
window.onload = function() {
    threeStart();
};

var canvas3d, width, height, stats;
var camera, scene, renderer, light;
var mouseX = 0, mouseY = 0;

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

function initThree() {

    //renderer = new THREE.WebGLRenderer({antialias : true});
    //IE only can run in this model
    renderer = new THREE.CanvasRenderer({antialias : true});

    renderer.setSize(width, height);
    canvas3d.appendChild(renderer.domElement);
    renderer.setClearColor(0x000000, 1.0);

}

function initCamera() {

    camera = new THREE.PerspectiveCamera(75, width / height, 1, 10000);
    camera.position.x = 0;
    camera.position.y = 0;
    camera.position.z = 1400;
    camera.up.x = 0;
    camera.up.y = 1;
    camera.up.z = 0;
    camera.lookAt({
        x : 0,
        y : 0,
        z : 0
    });
}

function initScene() {
    scene = new THREE.Scene();
    scene.fog = new THREE.FogExp2(0x000000, 0.0007);
}

function initStatsWatch() {
    stats = new Stats();
    stats.setMode(2);
    // 0: fps, 1: ms, 2: both
    stats.domElement.style.position = 'absolute';
    stats.domElement.style.top = '0px';
    document.getElementById('canvas3d').appendChild(stats.domElement);
}

function initLights() {
    //var ambientLight = new THREE.AmbientLight(0xFFFFF);
    //scene.add(ambientLight);
}

function threeStart() {

    canvas3d = document.getElementById('canvas3d');
    width = canvas3d.clientWidth;
    height = canvas3d.clientHeight;

    initThree();
    initCamera();
    initScene();
    initLights();
    initStatsWatch();
    initObjects();

    renderer.render(scene, camera);

    animate();

    document.addEventListener('mousemove', onDocumentMouseMove, false);
    document.addEventListener('touchstart', onDocumentTouchStart, false);
    document.addEventListener('touchmove', onDocumentTouchMove, false);
    window.addEventListener('resize', onWindowResize, false);

}

function onWindowResize() {

    windowHalfX = window.innerWidth / 2;
    windowHalfY = window.innerHeight / 2;

    width = canvas3d.clientWidth;
    height = canvas3d.clientHeight;
    renderer.setSize(width, height);
    initCamera();
}

function onDocumentMouseMove(event) {

    mouseX = event.clientX - windowHalfX;
    mouseY = event.clientY - windowHalfY;

}

function onDocumentTouchStart(event) {
    if (event.touches.length === 1) {
        event.preventDefault();
        mouseX = event.touches[0].pageX - windowHalfX;
        mouseY = event.touches[0].pageY - windowHalfY;
    }
}

function onDocumentTouchMove(event) {

    if (event.touches.length === 1) {

        event.preventDefault();

        mouseX = event.touches[0].pageX - windowHalfX;
        mouseY = event.touches[0].pageY - windowHalfY;
    }

}

function animate() {

    requestAnimationFrame(animate);

    render();
    stats.update();

}

